<template>
  <div>
    <el-form-item v-if="editorForm.content.canChoose" label="文字类型">
      <el-radio-group v-model="editorForm.content.type" @change="handleChangeType">
        <el-radio label="custom">自定义</el-radio>
        <el-radio label="category">栏目名称</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="editorForm.content.type === 'custom'" label="文字内容">
      <el-input v-model="editorForm.content.custom" placeholder="请输入" @input="handleChange" />
    </el-form-item>
  </div>
</template>

<script setup>
import { inject, ref, onMounted } from 'vue'

const { editorForm, domList, backUpdate, updateGlobalProp } = inject('commonForm')
// 初始化属性和元素对应关系
const bindDom = ref(new Set())
const initDomMapping = () => {
  const bindKeys = [`${editorForm.value._key}.content.custom`]
  domList.value.forEach(element => {
    const bindValue = element.getAttribute('_bind')
    bindKeys.forEach(key => {
      if (bindValue.includes(key)) {
        bindDom.value.add(element)
      }
    })
  })
}

const handleChangeType = () => {
  if (editorForm.value.content.globalId) {
    const prop = { content: editorForm.value.content }
    updateGlobalProp(editorForm.value.content.globalId, prop)
    return
  }
  if (editorForm.value.content.type === 'category') {
    backUpdate()
  } else {
    handleChange()
  }
}

const handleChange = () => {
  if (editorForm.value.content.globalId) {
    const prop = { content: editorForm.value.content }
    updateGlobalProp(editorForm.value.content.globalId, prop)
    return
  }
  bindDom.value.forEach(element => {
    element.textContent = editorForm.value.content.custom
  })
  if (bindDom.value.size === 0) {
    backUpdate()
  }
}

onMounted(() => {
  initDomMapping()
})
</script>

<style lang='scss' scoped></style>